package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.NavDao;
import com.cn.wanxi.dao.impl.NavImpl;
import com.cn.wanxi.model.NavModel;
import com.cn.wanxi.service.NavService;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

public class NavServiceImpl implements NavService {
    @Override
    public List<NavModel> findAll() {
        boolean isHave = false;
        List<NavModel> list = new ArrayList<>();
        Jedis jedis = new Jedis();
        jedis.select(1);
        isHave = jedis.exists("navModelHref");
        if (isHave) {
//            long length = jedis.llen("navModelTitle");
            List<String> navModelTitle = jedis.lrange("navModelTitle", 0, -1);
            List<String> navModelHref = jedis.lrange("navModelHref", 0, -1);
            for (int i = 0; i < navModelTitle.size(); i++) {
                NavModel model = new NavModel();
                model.setTitle(navModelTitle.get(i));
                model.setHref(navModelHref.get(i));
                list.add(model);
            }
        } else {
            NavDao navDao = new NavImpl();
            list = navDao.findAll();
            for (NavModel model :
                    list) {
                jedis.rpush("navModelHref", model.getHref());
                jedis.rpush("navModelTitle", model.getTitle());
            }

        }

        return list;
    }

    /**
     * 只要设计到更新操作，都要把当前的key值删除
     * @param navModel
     * @return
     */
    public String add(NavModel navModel) {
        NavDao navDao = new NavImpl();
        int result = navDao.add(navModel);
        if (result > 0) {
            Jedis jedis = new Jedis();
            jedis.select(1);
            jedis.del("navModelHref", "navModelTitle");
        }
        return result > 0 ? "success" : "error";
    }
}
